package com.lmz.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.lmz.common.TO.mq.SeckillOrderTo;
import com.lmz.common.utils.R;
import com.lmz.common.vo.MemberResponseVo;
import com.lmz.seckill.feign.couponFeignServie;
import com.lmz.seckill.feign.productFeignService;
import com.lmz.seckill.interceptor.LoginUserInterceptor;
import com.lmz.seckill.service.SeckillService;
import com.lmz.seckill.to.SekillSkuRedisTo;
import com.lmz.seckill.vo.SeckillSessionWithSkus;
import com.lmz.seckill.vo.SkuInfoVo;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class SeckillServiceImpl implements SeckillService {

    private final String SESSION_CACHE_PREFIX = "seckill:sessions:";
    private final String SKUKILL_CACHE_PREFIX = "seckill:skus:";
    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";

    @Autowired
    private couponFeignServie couponFeignServie;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private productFeignService productFeignService;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 上架商品
     */
    @Override
    public void uploadSeckillSku() {
        //查询需要上架的商品
        R r = couponFeignServie.getLates3DatSession();
        if (r.getCode() == 0) {
            //上架商品
            List<SeckillSessionWithSkus> data = r.getData("data", new TypeReference<List<SeckillSessionWithSkus>>() {
            });
            //将数据缓存到redis中
            //1.缓存活动信息
            saveSessionInfos(data);
            //2.缓存活动关联的商品信息
            saveSessionSkuInfos(data);
        }
    }

    @Override
    public List<SekillSkuRedisTo> getCurrentTimeSeckillSkus() {
        //1.确定当前时间属于哪个秒杀场次
        long now = new Date().getTime();
        Set<String> keys = redisTemplate.keys(SESSION_CACHE_PREFIX + "*");
        for (String key : keys) {
            String replace = key.replace(SESSION_CACHE_PREFIX, "");
            String[] s = replace.split("_");
            long startTime = Long.parseLong(s[0]);
            long endTime = Long.parseLong(s[1]);
            if (now >= startTime && now <= endTime) {
                List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                List<String> list = ops.multiGet(range);
                if (list != null) {
                    List<SekillSkuRedisTo> collect = list.stream().map(item -> {
                        SekillSkuRedisTo redisTo = JSON.parseObject(item.toString(), SekillSkuRedisTo.class);
                        //秒杀未开始则不能传递随机码
                        //redisTo.setRandomCode(null);
                        return redisTo;
                    }).collect(Collectors.toList());
                    return collect;
                }
                break;
            }
        }
        //2.获取当前场次所需要的信息
        return null;
    }

    @Override
    public SekillSkuRedisTo skuSeckillInfo(Long skuId) {
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = ops.keys();
        if (keys != null && keys.size() > 0) {
            String reg = "\\d_" + skuId;
            for (String key : keys) {
                boolean matches = Pattern.matches(reg, key);
                if (matches) {
                    String res = ops.get(key);
                    SekillSkuRedisTo sekillSkuRedisTo = JSON.parseObject(res, SekillSkuRedisTo.class);
                    //判断随机码是否应该返回
                    Long startTime = sekillSkuRedisTo.getStartTime();
                    Long endTime = sekillSkuRedisTo.getEndTime();
                    long now = new Date().getTime();
                    if (now <= startTime || now >= endTime) {
                        sekillSkuRedisTo.setRandomCode(null);
                    }
                    return sekillSkuRedisTo;
                }
            }
        }
        return null;
    }


    /**
     * 保存活动信息
     */
    private void saveSessionInfos(List<SeckillSessionWithSkus> data) {
        for (SeckillSessionWithSkus session : data) {
            Long startTime = session.getStartTime().getTime();
            Long endTime = session.getEndTime().getTime();
            String key = SESSION_CACHE_PREFIX + startTime + "_" + endTime;
            Boolean hasKey = redisTemplate.hasKey(key);
            if (!hasKey) {
                List<String> collect = session.getRelationSkus().stream().map(item -> item.getPromotionSessionId().toString()
                        + "_" + item.getSkuId().toString()).collect(Collectors.toList());

                redisTemplate.opsForList().leftPushAll(key, collect);
            }
        }
    }

    /**
     * 保存活动关联的商品信息
     */
    private void saveSessionSkuInfos(List<SeckillSessionWithSkus> data) {
        for (SeckillSessionWithSkus session : data) {
            //绑定哈希
            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            session.getRelationSkus().forEach(item -> {
                String token = UUID.randomUUID().toString().replace("-", "");
                if (!ops.hasKey(item.getPromotionId().toString() + "_" + item.getSkuId().toString())) {
                    SekillSkuRedisTo redisTo = new SekillSkuRedisTo();
                    //sku基本信息
                    R r = productFeignService.skuInfo(item.getSkuId());
                    if (r.getCode() == 0) {
                        SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        redisTo.setSkuInfoVo(skuInfo);
                    }
                    //sku秒杀信息
                    BeanUtils.copyProperties(item, redisTo);
                    //开始结束时间
                    redisTo.setStartTime(session.getStartTime().getTime());
                    redisTo.setEndTime(session.getEndTime().getTime());
                    //引入随机码  防止直接根据商品id进行脚本抢购
                    redisTo.setRandomCode(token);
                    String dataRedis = JSON.toJSONString(redisTo);
                    ops.put(item.getPromotionId().toString() + "_" + item.getSkuId().toString(), dataRedis);

                    //如果当前场次的库存信息已经上架就不需要再上架
                    //通过信号量表示库存，应对高并发
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    semaphore.trySetPermits(item.getSeckillCount());
                }
            });
        }
    }

    /**
     * 秒杀业务
     */
    @Override
    public String kill(String killId, String key, Integer num) {
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();

        //获取秒杀商品的详细信息
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String s = ops.get(killId);
        if (!StringUtils.isEmpty(s)) {

            SekillSkuRedisTo redisData = JSON.parseObject(s, SekillSkuRedisTo.class);
            //校验合法性
            Long startTime = redisData.getStartTime();
            Long endTime = redisData.getEndTime();
            long now = new Date().getTime();
            long ttl = endTime - startTime;

            //秒杀是否时间对应
            if (now >= startTime && now <= endTime) {
                //校验随机码和商品id
                String randomCode = redisData.getRandomCode();
                String sku_Id = redisData.getPromotionSessionId() + "_" + redisData.getSkuId();
                if (randomCode.equals(key) && killId.equals(sku_Id)) {
                    //验证购物的数量
                    if (num <= redisData.getSeckillLimit()) {
                        //是否已经购买过,幂等性，不能多次重复购买 userId_sessionId_skuId存入redis
                        String redisKey = memberResponseVo.getId() + "_" + sku_Id;
                        //不存在才能插入数据
                        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if (ifAbsent) {
                            //成功表明未购买
                            //通过信号量判断是否还要库存
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                            //尝试获取信号量，不能是阻塞获取
                            try {
                                boolean isGet = semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);
                                if (isGet) {
                                    String orderSn = IdWorker.getTimeId();
                                    //秒杀成功，快速下单并给mq发送消息
                                    SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
                                    seckillOrderTo.setOrderSn(orderSn);
                                    seckillOrderTo.setMemberId(memberResponseVo.getId());
                                    seckillOrderTo.setNum(num);
                                    seckillOrderTo.setPromotionSessionId(redisData.getPromotionSessionId());
                                    seckillOrderTo.setSkuId(redisData.getSkuId());
                                    seckillOrderTo.setSeckillPrice(redisData.getSeckillPrice());

                                    rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", seckillOrderTo);
                                    return orderSn;
                                }
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                                return null;
                            }
                        }
                    }
                }
            }
        }
        return null;
    }


}